<template>
	<view class="customer-form">
		<!-- 导航栏 -->

		<scroll-view class="form-content" scroll-y="true">
			<!-- 基础信息 -->
			<view class="form-section">
				<view class="form-grid">
					<!-- 姓名 -->
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">姓名</text>
							<text class="item-required">*</text>
						</view>
						<uni-easyinput class="item-input" type="text" placeholder="请输入姓名" v-model="formData.customerName"  :disabled="eidit"
							@blur="validateField('customerName')" :inputBorder="false" />
						<text class="error-msg" v-if="errors.customerName">{{ errors.customerName }}</text>
					</view>
					
					<!-- 手机号 -->
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">手机号码</text>
							<text class="item-required">*</text>
						</view>
						<uni-easyinput class="item-input" type="number" placeholder="请输入手机号码" v-model="formData.phone" 
							@blur="validateField('phone')" :inputBorder="false" disabled />
						<text class="error-msg" v-if="errors.phone">{{ errors.phone }}</text>
					</view>
					
					<!-- 性别 -->
					<view class="form-item">
						<text class="item-label">性别</text>
						<view class="radio-group">
							<view class="radio-option" :class="{ active: formData.gender === 'male' }"
								@click="formData.gender = 'male'">
								<view class="radio-dot"></view>
								<text class="radio-text">男</text>
							</view>
							<view class="radio-option" :class="{ active: formData.gender === 'female' }"
								@click="formData.gender = 'female'">
								<view class="radio-dot"></view>
								<text class="radio-text">女</text>
							</view>
						</view>
					</view>

					<!-- 身份证号 -->
					<view class="form-item">
						<view class="label-row">
							<text class="item-label">身份证号</text>
						</view>
						<uni-easyinput class="item-input" type="idcard" placeholder="请输入身份证号码" v-model="formData.idCard"
							:inputBorder="false" />
					</view>

				<!-- 	<view class="form-item">
						<text class="item-label">职业</text>
						<picker class="item-picker" mode="selector" :range="jobOptions" @change="onJobChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.job || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
					
					<view class="form-item">
						<text class="item-label">微信号</text>
						<uni-easyinput class="item-input" type="text" placeholder="请输入微信号" v-model="formData.wechat"
							:inputBorder="false" />
					</view>
					
					<view class="form-item full-width">
						<text class="item-label">居住地址</text>
						<uni-easyinput class="item-input" type="text" placeholder="请输入居住地址" v-model="formData.address"
							:inputBorder="false" />
					</view> -->
				</view>
			</view>

			<!-- 家庭信息 -->
			<!-- <view class="form-section">
				<view class="form-grid">
					<view class="form-item">
						<text class="item-label">婚姻状况</text>
						<picker class="item-picker" mode="selector" :range="marriageOptions" @change="onMarriageChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.marriage || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>

					<template v-if="showChildrenField">
						<view class="form-item">
							<text class="item-label">是否有小孩</text>
							<view class="radio-group">
								<view class="radio-option" :class="{ active: formData.hasChildren === 'yes' }"
									@click="formData.hasChildren = 'yes'">
									<view class="radio-dot"></view>
									<text class="radio-text">是</text>
								</view>
								<view class="radio-option" :class="{ active: formData.hasChildren === 'no' }"
									@click="formData.hasChildren = 'no'">
									<view class="radio-dot"></view>
									<text class="radio-text">否</text>
								</view>
							</view>
						</view>

						<view class="form-item" v-if="formData.hasChildren === 'yes'">
							<text class="item-label">孩子数量</text>
							<picker class="item-picker" mode="selector" :range="childrenCountOptions"
								@change="onChildrenCountChange">
								<view class="picker-content">
									<text class="picker-text">{{ formData.childrenCount || '请选择' }}</text>
									<text class="picker-arrow">▼</text>
								</view>
							</picker>
						</view>
					</template>
					
					<view class="form-item">
						<text class="item-label">收入</text>
						<picker class="item-picker" mode="selector" :range="incomeOptions" @change="onIncomeChange">
							<view class="picker-content">
								<text class="picker-text">{{ formData.income || '请选择' }}</text>
								<text class="picker-arrow">▼</text>
							</view>
						</picker>
					</view>
				</view>
			</view> -->

			<!-- 备注信息 -->
			<view class="form-section">
				<view class="form-item full-width">
					<text class="item-label">备注</text>
					<uni-easyinput type="textarea" v-model="formData.remark" autoHeight placeholder="请输入备注信息"></uni-easyinput>
				</view>
			</view>
			
			<view class="form-section" v-if="$userInfo.role ==4">
				<view class="form-grid">
				<view class="section-title">
					中介信息 
					<template v-if="$userInfo.role!=4 && formData.zhongjieName" >【{{formData.zhongjieName}}】</template>
				</view>
				
				<view class="form-item">
					<text class="item-label">业务员姓名</text>
					<uni-easyinput class="item-input" type="text" placeholder="请输入业务员姓名" v-model="formData.zhongjieYWYName" :disabled="$userInfo.role !=4" :inputBorder="false" />
				</view>
				<view class="form-item">
					<text class="item-label">业务员电话</text>
					<uni-easyinput class="item-input" type="text" placeholder="请输入业务员电话" v-model="formData.zhongjieYWYPhone" :disabled="$userInfo.role !=4" :inputBorder="false" />
				</view>
				<view class="form-item">
					<text class="item-label">业务员门市</text>
					<uni-easyinput class="item-input" type="text" placeholder="请输入业务员门市" v-model="formData.zhongjieYWYShop" :disabled="$userInfo.role !=4" :inputBorder="false" />
				</view>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="action-section">
				<button class=" btn-primary" @tap="submitForm" :disabled="isSubmitting">
					<text class="btn-text">{{ isSubmitting ? '提交中...' : isEdit ? '保存修改' : '确认提交' }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				customerId: '',
				formData: {
					customerName: '',
					gender: 'male',
					idCard: '',
					phone: '',
					wechat: '',
					job: '',
					marriage: '',
					income: '',
					hasChildren: '',
					childrenCount: '',
					address: '',
					remark: ''
				},
				errors: {
					customerName: '',
					phone: ''
				},
				isSubmitting: false,
				marriageOptions: [
					'未婚',
					'已婚',
					'离异',
					'丧偶'
				],
				incomeOptions: [
					'10-20万',
					'20-30万',
					'30-50万',
					'50万以上'
				],
				childrenCountOptions: [
					'1个',
					'2个',
					'3个',
					'4个及以上'
				],
				jobOptions: [
					'私企职员',
					'国企职员',
					'事业单位',
					'个体经营者',
					'自由职业者',
					'学生',
					'教师',
					'医生',
					'工程师',
					'设计师',
					'销售人员',
					'管理人员',
					'其他'
				],
				eidit:false
			}
		},
		onLoad(option) {
			// 设置页面标题
			uni.setNavigationBarTitle({
				title: this.isEdit ? '编辑客户' : '添加客户'
			});
			
			// 如果是编辑模式，获取客户信息
			if (option.id) {
				this.isEdit = true;
				this.customerId = option.id;
				this.getCustomerDetail();
			}
            let phone = option.phone
			let isPhone = /^1[3-9]\d{9}$/.test(phone)
			if (isPhone) {
				this.formData.phone = phone
			}else if(phone.length === 7){
				this.formData.phone = phone
			}
		},
		computed: {
			showChildrenField() {
				return this.formData.marriage !== '未婚' && this.formData.marriage;
			}
		},
		methods: {
			// 获取客户详情
			async getCustomerDetail() {
				try {
					const res = await this.$cloudObject('middleman-advisor-customers').getCustomerById({
						id: this.customerId
					});
					
					if (res.resultCode === 0) {
						this.formData = {
							...this.formData,
							...res.data
						};
					} else {
						this.$simpleToast(res.message || '获取客户信息失败');
					}
				} catch (error) {
					console.error('获取客户详情失败:', error);
					this.$simpleToast('获取客户信息失败');
				}
			},
			
			// 验证字段
			validateField(field) {
				const value = this.formData[field];
				switch (field) {
					case 'customerName':
						this.errors.customerName = !value ? '请输入姓名' : value.length < 2 ? '姓名至少2个字符' : '';
						break;
					case 'phone':
						this.errors.phone = !value ? '请输入手机号' : !/^(1\d{6}|1[3-9]\d{9})$/.test(value) ? '手机号格式不正确' : '';
						break;
				}
			},
			
			// 职业选择
			onJobChange(e) {
				const index = e.detail.value;
				this.formData.job = this.jobOptions[index];
			},
			
			// 婚姻状况选择
			onMarriageChange(e) {
				const index = e.detail.value;
				this.formData.marriage = this.marriageOptions[index];
				// 重置相关的子字段
				this.formData.hasChildren = '';
				this.formData.childrenCount = '';
			},
			
			// 收入选择
			onIncomeChange(e) {
				const index = e.detail.value;
				this.formData.income = this.incomeOptions[index];
			},
			
			// 孩子数量选择
			onChildrenCountChange(e) {
				const index = e.detail.value;
				this.formData.childrenCount = this.childrenCountOptions[index];
			},
			
			// 提交表单
			async submitForm() {
				// 验证必填字段
				this.validateField('customerName');
				this.validateField('phone');
				
				if (this.errors.customerName || this.errors.phone) {
					return this.$simpleToast('请完善必填信息');
				}
				
				let phone = this.formData.phone
                if(phone.length === 7){
					 const prefix = phone.substring(0, 3);
					const suffix = phone.substring(3);
					phone = prefix + '****' + suffix;
				}
				this.formData.phone = phone
				this.isSubmitting = true;
				try {
					let result;
					
					if (this.isEdit) {
						// 编辑模式
						result = await this.$cloudOBjAjax('middleman-advisor-customers','updateCustomer',{
							id: this.customerId,
							...this.formData
						});
					} else {
						// 添加模式
						// 根据用户角色设置创建者类型和相关信息
						const userInfo = this.$userInfo;
						const postData = { ...this.formData };
						
						// 设置创建者信息
						if (userInfo.role === 4 || userInfo.role === 5) {
							// 中介
							postData.creatorType = 1;
							postData.middlemanId = userInfo._id;
							postData.middlemanName = userInfo.agency;
							postData.typeMap = 2
							
						} else if (userInfo.role === 3) {
							// 置业顾问
							postData.creatorType = 2;
							postData.typeMap = 3
							postData.advisorId = userInfo._id;
							postData.middlemanId = userInfo._id;
							postData.advisorName = userInfo.nickName;
						}
						
						result = await this.$cloudOBjAjax('middleman-advisor-customers','addCustomer',postData);
					}
					
					if (result) {
						this.$simpleToast(this.isEdit ? '保存成功' : '添加成功');
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						this.$simpleToast(result.message || (this.isEdit ? '保存失败' : '添加失败'));
					}
				} catch (error) {
					console.error('提交表单失败:', error);
					this.$simpleToast(this.isEdit ? '保存失败' : '添加失败');
				} finally {
					this.isSubmitting = false;
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.customer-form {
		min-height: 100%;
		background: #f8f9fa;
	}
	
	.header {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding: 60rpx 40rpx 40rpx;
		color: white;
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	/* 表单内容 */
	.form-content {
		padding: 30rpx;
		padding-bottom: 40rpx;
		box-sizing: border-box;
	}
	
	/* 表单区域 */
	.form-section {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}
	
	/* 表单网格布局 */
	.form-grid {
		display: grid;
		gap: 30rpx;
	}
	
	.form-item {
		display: flex;
		flex-direction: column;
	}
	
	.form-item.full-width {
		grid-column: 1 / -1;
	}
	
	.label-row {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.item-label {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
        margin-bottom: 10rpx;
	}
	
	.item-required {
		color: #ff4757;
		margin-left: 4rpx;
		font-size: 24rpx;
	}
	
	.error-msg {
		color: #ff4757;
		font-size: 24rpx;
		margin-top: 8rpx;
	}
	
	/* 输入框样式 */
	::v-deep .uni-easyinput__content {
		border: 2rpx solid #e0e0e0 !important;
		border-radius: 12rpx !important;
		background: #fafafa !important;
		transition: all 0.3s;
	}
	
	::v-deep .uni-easyinput__content:focus-within {
		border-color: #FF9500 !important;
		background: white !important;
		box-shadow: 0 0 0 4rpx rgba(255, 149, 0, 0.1) !important;
	}
	
	/* 单选组样式 */
	.radio-group {
		display: flex;
		gap: 20rpx;
	}
	
	.radio-option {
		display: flex;
		align-items: center;
		padding: 16rpx 24rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fafafa;
		transition: all 0.3s;
	}
	
	.radio-option.active {
		border-color: #FF9500;
		background: #fffaf0;
	}
	
	.radio-dot {
		width: 24rpx;
		height: 24rpx;
		border: 2rpx solid #ccc;
		border-radius: 50%;
		margin-right: 12rpx;
		position: relative;
	}
	
	.radio-option.active .radio-dot {
		border-color: #FF9500;
		background: #FF9500;
	}
	
	.radio-text {
		font-size: 26rpx;
		color: #333;
	}
	
	/* 选择器样式 */
	.picker-content {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		background: #fafafa;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.picker-text {
		font-size: 28rpx;
		color: #333;
	}
	
	.picker-text:placeholder {
		color: #999;
	}
	
	.picker-arrow {
		color: #999;
		font-size: 24rpx;
	}
	
	/* 提交按钮 */
	.action-section {
		padding: 40rpx 0;
	}
	
	.submit-btn {
		background: linear-gradient(135deg, #FFA500 0%, #FF8C00 100%);
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 30rpx;
		font-weight: 600;
		box-shadow: 0 4rpx 16rpx rgba(255, 149, 0, 0.3);
		transition: all 0.3s;
		line-height: 70rpx;
		height: 70rpx;
	}
	
	.submit-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(255, 149, 0, 0.3);
	}
	
	.submit-btn:disabled {
		opacity: 0.6;
	}
	
	.btn-text {
		font-size: 30rpx;
	}
	
</style>